using EFCoreEnterpriseDemo.Services;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace EFCoreEnterpriseDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IUserService _userService;

        public UsersController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpGet]
        public async Task<IActionResult> GetUsers([FromQuery] UserSearchCriteria criteria)
        {
            var result = await _userService.GetUsersAsync(criteria);
            return Ok(result);
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetUser(int id)
        {
            var user = await _userService.GetUserByIdAsync(id);
            return user == null ? NotFound() : Ok(user);
        }

        [HttpPost]
        public async Task<IActionResult> CreateUser([FromBody] CreateUserDto dto)
        {
            var id = await _userService.CreateUserAsync(dto);
            return CreatedAtAction(nameof(GetUser), new { id }, new { id });
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateUser(int id, [FromBody] UpdateUserDto dto)
        {
            await _userService.UpdateUserAsync(id, dto);
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            await _userService.SoftDeleteUserAsync(id);
            return NoContent();
        }

        [HttpPost("{id}/restore")]
        public async Task<IActionResult> RestoreUser(int id)
        {
            await _userService.RestoreUserAsync(id);
            return NoContent();
        }

        [HttpGet("export")]
        public async Task<IActionResult> ExportUsers([FromQuery] UserExportCriteria criteria)
        {
            var data = await _userService.ExportUsersAsync(criteria);
            return File(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "users.xlsx");
        }

        [HttpPost("import")]
        public async Task<IActionResult> ImportUsers([FromForm] IFormFile file)
        {
            using var stream = file.OpenReadStream();
            var result = await _userService.ImportUsersAsync(stream);
            return Ok(result);
        }
    }
}